import MaskText from '@/components/MaskText';
import { fenceUserTypeHash } from '.';
import Ellipsis from '../../../components/Ellipsis';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';
import WarningConfigModal from './warningConfigModal';
import { filterAuth } from '@/support/common';
import { downloadFileByUrl } from '@/utils/utils';
import { ExportOutlined, PlusOutlined, ImportOutlined, UploadOutlined } from '@ant-design/icons';
import { Card, Button, Modal, Descriptions, Upload, message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';
import router from 'umi/router';
import * as XLSX from 'xlsx';

const mapStateToProps = (state: any) => ({
  electricFenceMng: state.electricFenceMng,
  loading: state.loading.effects['electricFenceMng/getFetchPage'],
});
class DistrictFence extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: { fenceType: 1 },
      uploadVisible: false,
      templateFileUrl: null,
      exportLoading: false,
      imports: [],
      importLoading: false,
      saveLoading: false,
      dealerData: [],
      importSuccessNum: 0,
      importFailNum: 0,
      importResultExcelUrl: '',
      importResultModalShow: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    this.refreshTable();
    dispatch({
      type: 'electricFenceMng/getData',
      payload: { url: '/common/template/detail', templateCode: 'districtFenceImport' },
      callback: (res: any) => {
        this.setState({ templateFileUrl: res.data ? res.data.templateUrl : null });
      },
    });
    dispatch({
      type: 'basedata/fetchDealerByLogin',
      callback: (response: { data: { name: any; code: any }[] }) => {
        //  需求迭代20231211：显示内容为“经销商名称(经销商编码)”
        const dealerData = response?.data?.map((o: { name: any; code: any }) => {
          return {
            label: `${o.name}(${o.code})`,
            value: o.code,
          };
        });
        this.setState({
          dealerData: dealerData || [],
        });
      },
    });
  }

  // initDealerData = () => {
  //   this.setState({ dealerData: [] });

  //   const dealTreeData = (orgParent, list) => {
  //     const arr =
  //       list
  //         .map((e) => ({
  //           orgParent: e.orgParent,
  //           sid: e.sid,
  //           value: e.orgCode,
  //           label: e.orgName,
  //         }))
  //         .filter((c) => c.orgParent === orgParent) || [];
  //     arr.forEach((item) => {
  //       const children = dealTreeData(item.sid, list);
  //       if (children.length) {
  //         item.children = children;
  //       }
  //     });
  //     return arr;
  //   };

  //   this.props.dispatch({
  //     type: 'http/getData',
  //     payload: {
  //       url: '/org/findorglistbytoken',
  //     },
  //     // callback: res => {
  //     //   if (res.statusCode === '0' && res.data && res.data.length) {
  //     //     const orgData = res.data;
  //     //     const current = orgData[0];
  //     //     if (current.orgType === 3) {
  //     //       // todo: 如果是授信机构, 是另外的逻辑, 待实现
  //     //       return;
  //     //     } else {
  //     //       this.setState({
  //     //         dealerData: [
  //     //           {
  //     //             label: current.orgName,
  //     //             value: current.orgCode,
  //     //             children: dealTreeData(
  //     //               current.sid,
  //     //               orgData.filter(e => [1, 2].indexOf(e.orgType) >= 0),
  //     //             ),
  //     //           },
  //     //         ],
  //     //       });
  //     //     }
  //     //   }
  //     // },
  //     callback: (res: any) => {
  //       if (res.statusCode === '0' && res.data && res.data.length) {
  //         let orgData = res.data;
  //         const current = orgData[0];
  //         orgData = orgData.filter((item: any) => item.orgType === 2);
  //         if (current.orgType === 3) {
  //           // todo: 如果是授信机构, 是另外的逻辑, 待实现
  //           return;
  //         } else {
  //           this.setState({
  //             dealerData: dealTreeData(current.sid, orgData),
  //           });
  //         }
  //       }
  //     },
  //   });
  // };

  refreshTable = () =>
    this.props.dispatch({
      type: 'electricFenceMng/getFetchPage',
      payload: { url: '/electricfence/findfencebypage', fenceType: 1 },
    });

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/initData',
    });
  }

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'electricFenceMng/getFetchPage',
      payload: { url: '/electricfence/findfencebypage', ...formValues },
    });
  };

  handleRemove = (id: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/delData',
      payload: {
        url: '/electricfence/deletefence?fenceId=' + id,
      },
      callback: (res: any) => {
        message.success('删除成功');
        this.handleFlushPage();
      },
    });
  };
  // 关联授信车辆
  handleRelative = ({ fenceId, dealerCode, orgId }) => {
    sessionStorage.setItem('dealerCode', dealerCode);
    sessionStorage.setItem('fenceId', fenceId);
    sessionStorage.setItem('fenceOrgId', orgId);
    router.push({
      pathname: '/electricFence/electricFenceMng/relateVehicle',
      query: { fenceId },
    });
  };
  onRef = ref => {
    this.warningConfigModalRef = ref;
  };

  // 设置预警方式
  setWarningConfig = record => {
    this.warningConfigModalRef.showModal(record);
  };

  beforeFileUpload = async (file: any) => {
    if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
      message.warning('请上传xlsx格式文件');
      return false;
    }
    if (file.size / 1024 / 1024 > 10) {
      message.warning('文件大小不能大于10MB');
      return false;
    }

    this.setState({ importLoading: true });
    const imports = await new Promise(resolve => {
      const reader = new FileReader();
      reader.onload = function (e: any) {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array', cellDates: true });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        let res = XLSX.utils.sheet_to_json(worksheet, { header: 1 }).slice(1);
        // 0-所属组织 1-经销商, 2-预警配置, 3-省, 4-市, 5-区, 6-开始时间, 7-结束时间， 8-围栏类型
        res = res || [];
        const imports = [];
        for (let i = 0; i < res.length; i++) {
          let e = res[i];
          e = e || [];
          if (!e.join('')) {
            // 过滤全部为空行的情况
            continue;
          }
          const orgCode = e[0];
          const dealerCode = e[1];
          // const warningConfigs =
          //   e && e[2]
          //     ? `${e[2]}`
          //         .split('_')
          //         .map((e) => parseInt(e))
          //         .filter((e) => e)
          //     : [];
          const repository = e[2];
          const provinceName = e[3];
          const cityName = e[4];
          const areaName = e[5];
          // 日期行如果有数据且不为日期格式
          if ((!!e[6] && !(e[6] instanceof Date)) || (!!e[7] && !(e[7] instanceof Date))) {
            message.error('导入文件参数异常，请检查！');
            return;
          }
          // excel转出的iso 8061时间差43s，+1h补齐到当日
          const warningBeginDate = !!e[6] ? moment(e[6]).add(1, 'h').format('YYYY-MM-DD') : '';
          const warningEndDate = !!e[7] ? moment(e[7]).add(1, 'h').format('YYYY-MM-DD') : '';
          const fenceUserType = e[8];
          imports.push({
            orgCode,
            dealerCode,
            // warningConfigs,
            repository,
            provinceName,
            cityName,
            areaName,
            warningBeginDate,
            warningEndDate,
            fenceUserType,
          });
        }
        resolve(imports);
      };
      reader.readAsArrayBuffer(file);
    })
      .catch(e => {})
      .finally(() => {
        this.setState({ importLoading: false });
      });

    this.setState({ imports: imports || [] });
    return false;
  };

  handleImport = async () => {
    const { dispatch } = this.props;
    this.setState({ saveLoading: true });
    const result = await dispatch({
      type: 'http/postObj',
      payload: {
        url: '/electricfence/importfence',
        data: this.state.imports,
      },
    });
    await this.setState({
      uploadVisible: false,
      imports: [],
      saveLoading: false,
      importSuccessNum: result?.data?.successNum || 0,
      importFailNum: result?.data ? result?.data?.failNum : '文件导入失败',
      importResultExcelUrl: result?.data?.resulExceltUrl,
      importResultModalShow: true,
    });
    this.refreshTable();
  };

  handleAdd = () => {
    router.push({
      pathname: `${self === top ? '' : '/external'}/electricFence/electricFenceMng/districtAdd`,
    });
  };

  handleEdit = (record: any) => {
    router.push({
      pathname: `${self === top ? '' : '/external'}/electricFence/electricFenceMng/districtAdd`,
      query: { fenceId: record.fenceId },
    });
  };

  handleDetail = (record: any) => {
    // router.push({
    //   pathname: `${self === top ? '' : '/external'}/electricFence/electricFenceMng/detailAndExport`,
    //   query: { fenceId: record.fenceId },
    // });
    router.push({
      pathname: `${self === top ? '' : '/external'}/electricFence/electricFenceMng/districtAdd`,
      query: { fenceId: record.fenceId, isDetail: true },
    });
  };

  handleExport = () => {
    const { dispatch } = this.props;
    this.setState({ exportLoading: true });
    dispatch({
      type: 'http/postObj',
      payload: {
        url: '/electricfence/exportfence',
        fenceName: this.state.formValues.fenceName,
        fenceType: 1,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          const data = [];
          res.data.forEach((e, i) => {
            const dealerName = e.dealerName ?? '';
            const dealerCode = e.dealerCode ?? '';
            data.push({
              index: i + 1,
              fenceCode: e.fenceCode,
              fenceName: e.fenceName,
              fenceUserType: fenceUserTypeHash[e.fenceUserType],
              orgName: e.orgName,
              dealer: dealerName + (dealerCode ? '(' + dealerCode + ')' : ''),
              // warningConfigDesc: any;
              // warningConfigDesc: e.warningConfigDesc,
              provinceName: e.provinceName,
              cityName: e.cityName,
              areaName: e.areaName,
              fenceExpireDate:
                e.warningBeginDate && e.warningEndDate
                  ? `${moment(e.warningBeginDate).format('YYYY-MM-DD')} ~ ${moment(
                      e.warningEndDate,
                    ).format('YYYY-MM-DD')}`
                  : '无限制',
              createBy: e.createBy,
              createDate: e.createDate ? moment(e.createDate).format('YYYY-MM-DD HH:mm:ss') : '',
            });
          });
          const header = {
            index: '序号',
            fenceCode: '围栏编号',
            fenceName: '围栏名称',
            fenceUserType: '围栏类型',
            orgName: '所属组织',
            dealer: '所属经销商',
            // warningConfigDesc: '预警方式',
            provinceName: '省级行政区',
            cityName: '市级行政区',
            areaName: '县级行政区',
            fenceExpireDate: '围栏有效期',
            createBy: '创建人',
            createDate: '创建时间',
          };
          const ws = XLSX.utils.json_to_sheet([header, ...data], { skipHeader: true });
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, 'export');
          const fileName = `行政区电子围栏${moment().format('YYYYMMDDHHmmss')}.xlsx`;
          XLSX.writeFile(wb, fileName);
        } else {
          message.error('导出失败');
        }
      },
    }).finally(() => this.setState({ exportLoading: false }));
  };

  render() {
    const {
      electricFenceMng: {
        pageData: { list, pagination },
      },
      loading,
      pathname,
      permissions,
      dispatch,
    } = this.props;
    const { formValues, uploadVisible, templateFileUrl, importResultModalShow, dealerData } =
      this.state;
    const columns = [
      {
        title: '围栏编号',
        dataIndex: 'fenceCode',
      },
      {
        title: '围栏名称',
        dataIndex: 'fenceName',
      },
      {
        title: '围栏类型',
        dataIndex: 'fenceUserType',
        render: (text: any) => fenceUserTypeHash[text + ''],
      },
      {
        title: '所属组织',
        dataIndex: 'orgName',
      },
      {
        title: '所属经销商',
        dataIndex: 'dealer',
        render: (text: any, record: any) => {
          const dealerName = record.dealerName ?? '';
          const dealerCode = record.dealerCode ?? '';

          return (
            <Ellipsis length={20} tooltip>
              {dealerName + (dealerCode ? '(' + dealerCode + ')' : '')}
            </Ellipsis>
          );
        },
      },
      // {
      //   title: '预警方式',
      //   dataIndex: 'warningConfigDesc',
      // },
      {
        title: '省级行政区',
        dataIndex: 'provinceName',
      },
      {
        title: '市级行政区',
        dataIndex: 'cityName',
      },
      {
        title: '县级行政区',
        dataIndex: 'areaName',
      },
      {
        title: '围栏有效期',
        render: (text: any) => {
          return text.warningBeginDate && text.warningEndDate
            ? `${moment(text.warningBeginDate).format('YYYY-MM-DD')} ~ ${moment(
                text.warningEndDate,
              ).format('YYYY-MM-DD')}`
            : '无限制';
        },
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: (text: any) => {
          return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null;
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 218,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '查看',
              key: 'detail',
              auth: 'electricFenceMng_doDetail',
              onConfirm: () => this.handleDetail(record),
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'electricFenceMng_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'electricFenceMng_doDel',
              Popconfirm: true,
              message: '是否确认删除？',
              onConfirm: () => this.handleRemove(record.fenceId),
            },
            {
              title: '设置预警方式',
              key: 'settingWarning',
              auth: 'electricFenceMng_doSettingWarningConfig',
              onConfirm: () => this.setWarningConfig(record),
            },
          ];
          const relativeBtn = {
            title: '关联授信车辆',
            key: 'relative',
            auth: 'electricFenceMng_doRelateVehicle',
            onConfirm: () => this.handleRelative(record),
          };
          if (record.fenceUserType === '1') btns.push(relativeBtn); // 围栏类型为经销商 显示关联授信车辆按钮
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.fenceId,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: '围栏名称',
        key: 'fenceName',
      },
      {
        type: 'select',
        title: '围栏类型',
        key: 'fenceUserType',
        selectOptions: [
          { value: '0', label: '非经销商' },
          { value: '1', label: '经销商' },
        ],
      },
      {
        type: 'select',
        title: '所属经销商',
        key: 'dealerCode',
        selectOptions: dealerData,
        keyValue: ['value', 'label'], //  取处理后的options的value和label
      },
      // {
      //   type: 'cascader',
      //   title: '经销商',
      //   key: 'dealerCode',
      //   selectOptions: this.state.dealerData,
      //   separator: '/',
      //   changeOnSelect: true,
      // },
    ];
    let isAdd = filterAuth('electricFenceMng_doAdd', permissions, pathname);
    let isBatchImport = filterAuth('electricFenceMng_doBatchImport', permissions, pathname);
    let isExport = filterAuth('electricFenceMng_doExport', permissions, pathname);
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{
              type: 'electricFenceMng/getFetchPage',
              url: '/electricfence/findfencebypage',
            }}
            extraArgs={{ fenceType: 1 }}
            saveFormValues={(val: any) => {
              // if (val.dealerCode && val.dealerCode.length) {
              //   val.dealerCode = val.dealerCode[val.dealerCode.length - 1];
              // }
              return this.setState({ formValues: Object.assign(formValues, val) });
            }}
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {isAdd || isExport || isBatchImport ? (
            <div className="my_newItem">
              {isAdd ? (
                <Button
                  size="small"
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={() => this.handleAdd()}
                >
                  新增
                </Button>
              ) : null}
              {isBatchImport ? (
                <Button
                  size="small"
                  icon={<ImportOutlined />}
                  type="primary"
                  onClick={() => this.setState({ uploadVisible: true })}
                >
                  批量导入
                </Button>
              ) : null}
              {isExport ? (
                <Button
                  size="small"
                  icon={<ExportOutlined />}
                  type="primary"
                  onClick={() => this.handleExport()}
                  loading={this.state.exportLoading}
                >
                  导出
                </Button>
              ) : null}
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'electricFenceMng/getFetchPage',
              url: '/electricfence/findfencebypage',
            }}
            formValues={formValues}
          />
          <Modal
            title="批量导入"
            visible={uploadVisible}
            okButtonProps={{ size: 'small' }}
            cancelButtonProps={{ size: 'small' }}
            onCancel={() => this.setState({ uploadVisible: false, imports: [] })}
            footer={[
              <Button
                loading={this.state.saveLoading}
                key="back"
                type="primary"
                size="small"
                onClick={this.handleImport}
              >
                保存
              </Button>,
            ]}
          >
            <Descriptions column={1} style={{ paddingTop: 10, paddingLeft: 8 }}>
              <Descriptions.Item label="模板">
                {/* {templateFileUrl ? (
                  <a href={templateFileUrl} title="点击下载模板文件">
                    下载模板文件
                  </a>
                ) : (
                  '暂无模板文件'
                )} */}
                {templateFileUrl ? (
                  <a
                    onClick={() => {
                      downloadFileByUrl(
                        templateFileUrl,
                        `批量导入行政区电子围栏${moment().format('YYYYMMDD')}.xlsx`,
                      );
                    }}
                  >
                    下载模板文件
                  </a>
                ) : (
                  '暂无模板文件'
                )}
              </Descriptions.Item>
              <Descriptions.Item label="文件" style={{ position: 'relative' }}>
                <Upload
                  className={styles.uploadFile}
                  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                  // onChange={this.handleFileChange}
                  // showUploadList={false}
                  beforeUpload={this.beforeFileUpload}
                  loading={this.state.importLoading}
                  maxCount={1}
                  onChange={e => {
                    if (e.file.status === 'removed') {
                      this.setState({
                        imports: [],
                        errorImports: [],
                      });
                    }
                  }}
                >
                  <Button size="small" icon={<UploadOutlined />} type="primary">
                    导入
                  </Button>
                </Upload>
                <div style={{ position: 'absolute', top: 2, left: 125 }}>
                  成功导入{this.state.imports.length}条
                </div>
              </Descriptions.Item>
            </Descriptions>
          </Modal>
          <Modal
            title="上传结果"
            visible={importResultModalShow}
            footer={null}
            onCancel={() => this.setState({ importResultModalShow: false })}
          >
            <p>上传成功：{this.state.importSuccessNum}</p>
            <p>上传失败：{this.state.importFailNum}</p>
            {this.state.importResultExcelUrl ? (
              <a href={this.state.importResultExcelUrl} title="点击下载结果文件">
                下载结果文件
              </a>
            ) : null}
          </Modal>
        </Card>
        <WarningConfigModal
          onRef={this.onRef}
          icon="plus"
          type="primary"
          dispatch={this.props.dispatch}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(DistrictFence);
